﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using FimetContoDeposito.BLL.Facades;
using FimetContoDeposito.BLL.Metadata;
using FimetContoDeposito.BLL.Objects;
using FimetContoDeposito.BLL.ResultSets;
using FimetContoDeposito.DAL;
using GrayParrot.Core;
using GrayParrot.Core.Json;
using GrayParrot.Web.Controls;
using GrayParrot.Web.Formly;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FimetContoDeposito.Controllers
{
    public class AnagraficaMagazziniController : GridCrudController<JObject, DTParameters>
    {
        #region Loading Fields...
        [HttpGet]
        public string LoadFields()
        {
            string retValue = null;

            var m_fields = FormlyHelper.ToFormly<AnagraficaMagazziniMetadata>(typeof(AnagraficaMagazziniMetadata));

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new NullToEmptyListResolver();
            settings.Converters = new List<JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false } };
            settings.Formatting = Formatting.Indented;
            settings.NullValueHandling = NullValueHandling.Ignore;

            retValue = JsonConvert.SerializeObject(m_fields, settings);

            return retValue;
        }

        [HttpGet]
        public string[] LoadFields(Guid id)
        {
            string[] retValue = new string[2] { string.Empty, string.Empty };

            FCD_Magazzini obj = null;
            using (MagazziniFacade m_dc = MagazziniFacade.Create())
            {
                ReturnValue<FCD_Magazzini> m_objs = m_dc.Get(id);
                if (m_objs.HasValue)
                {
                    obj = m_objs.Value;
                }
            }

            if (obj != null)
            {
                var m_fields = FormlyHelper.ToFormly<AnagraficaMagazziniMetadata>(typeof(AnagraficaMagazziniMetadata));

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ContractResolver = new NullToEmptyListResolver();
                settings.Converters = new List<JsonConverter> { 
                    new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false }
                };

                settings.Formatting = Formatting.Indented;
                settings.NullValueHandling = NullValueHandling.Ignore;

                retValue[0] = JsonConvert.SerializeObject(m_fields, settings);

                retValue[1] = JsonConvert.SerializeObject(obj);
            }
            else
            {
            }

            //
            return retValue;
        }        
        #endregion

        public override System.Net.Http.HttpResponseMessage Add(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            dynamic json = data;

            string m_messaggio = string.Empty;

            FCD_Magazzini obj = new FCD_Magazzini();
            obj.Id = Guid.NewGuid();
            obj.Nome = json.Nome;
            obj.Note = json.Note;
            obj.Abilitato = GrayParrot.Extensions.Types.TypeExtensions.GetValueOrDefault<bool>(json.Abilitato.ToString());
            obj.DataCreazione = DateTime.Now;
            obj.IdCustomer = Guid.Parse(json.IdCustomer.ToString());

            using (MagazziniFacade m_dc = MagazziniFacade.Create())
            {
                ReturnValue<bool> result = m_dc.Add(obj);

                if (result.HasValue)
                {
                    retValue = Request.CreateResponse(HttpStatusCode.OK, "Creazione Magazzino eseguita !");
                }
                else
                {
                    retValue = Request.CreateResponse(HttpStatusCode.OK, "Errore nella creazione del magazzino");
                }
            }

            return retValue;
        }

        public override System.Net.Http.HttpResponseMessage Edit(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            dynamic json = data;
            Guid m_id = Guid.Parse(json.Id.ToString());

            using (MagazziniFacade m_dc = MagazziniFacade.Create())
            {
                ReturnValue<FCD_Magazzini> m_ab = m_dc.Get(m_id);

                if (m_ab.HasValue)
                {
                    FCD_Magazzini obj = m_ab.Value;
                    obj.Nome = json.Nome;
                    obj.Note = json.Note;
                    obj.Abilitato = GrayParrot.Extensions.Types.TypeExtensions.GetValueOrDefault<bool>(json.Abilitato.ToString());
                    obj.DataCreazione = DateTime.Parse(json.DataCreazione.ToString());
                    obj.IdCustomer = Guid.Parse(json.IdCustomer.ToString());

                    ReturnValue<bool> result = m_dc.Edit(obj);

                    if (result.HasValue && result.Value)
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, "Modifica Magazzino Ok");
                    }
                }
                else
                {
                    retValue = Request.CreateResponse(HttpStatusCode.OK, "Magazzino non trovato");
                }
            }

            return retValue;
        }

        public override System.Net.Http.HttpResponseMessage Delete(int id)
        {
            throw new NotImplementedException();
        }

        [HttpPost]
        public override System.Net.Http.HttpResponseMessage Delete(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            dynamic json = data;
            Guid m_id = Guid.Parse(json.id.ToString());

            using (MagazziniFacade m_dc = MagazziniFacade.Create())
            {
                ReturnValue<FCD_Magazzini> m_obj = m_dc.Get(m_id);

                if (m_obj.HasValue)
                {
                    ReturnValue<bool> result = m_dc.Delete(m_obj.Value);
                    
                    if (result.HasValue)
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, "Cancellazione Magazzino effettuata !");
                    }
                    else
                    {
                        retValue = Request.CreateResponse(HttpStatusCode.OK, "Errore nella cancellazione del Magazzino");
                    }

                }
                else
                {
                    retValue = Request.CreateResponse(HttpStatusCode.OK, "Errore nella selezione del Magazzino");
                }
            }

            return retValue;
        }

        public override System.Net.Http.HttpResponseMessage Load(DTParameters data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            using (MagazziniFacade m_dc = MagazziniFacade.Create())
            {
                ReturnValue<IQueryable<FCD_Magazzini>> m_objs = m_dc.GetAllEx();

                DTResult<FCD_Magazzini> result = DTResult<FCD_Magazzini>.Empty("Nessun elemento trovato");
                if (m_objs.HasValue)
                {
                    MagazziniResultSet m_rs = new MagazziniResultSet(data, m_objs.Value);
                    result = m_rs.GetResult();
                }
                else
                {
                    if (m_objs.HasError)
                    {
                        result.Message.MessageType = MessageTypes.Error;
                        result.Message.Message = m_objs.Error.Message;
                    }
                }

                retValue = Request.CreateResponse(HttpStatusCode.OK, result);
            }

            return retValue;
        }
    }
}